//index.js
//获取应用实例
var mqtt = require('../../utils/mqtt.min.js') //根据自己存放的路径修改
const crypto = require('../../utils/hex_hmac_sha1.js');
const deviceConfig = {
  productKey: "xxxxx",
  deviceName: "xxxxx",
  deviceSecret: "xxxxxxx",
  regionId: "cn-shanghai"
};
const topics = {
  pubTopic: `/sys/${deviceConfig.productKey}/${deviceConfig.deviceName}/thing/event/property/post`,
  subTopic: `/sys/${deviceConfig.productKey}/${deviceConfig.deviceName}/thing/service/property/set`
}
var client;
Page({
  data: {
    humidity: "",
    temperature: "",
    a0: "湿度",
    wendu: "温度",
    imageUrl: "../../images/down.png",
    productKey: deviceConfig.productKey,
    deviceName: deviceConfig.deviceName,
    deviceSecret: deviceConfig.deviceSecret
  },
  // 设备身份三元组输入框事件处理函数
  productKeyInput: function (e) {
    deviceConfig.productKey = e.detail.value
    this.setData({ productKey: deviceConfig.productKey })
  },
  deviceNameInput: function (e) {
    deviceConfig.deviceName = e.detail.value
    this.setData({ deviceName: deviceConfig.deviceName })
  },
  deviceSecretInput: function (e) {
    deviceConfig.deviceSecret = e.detail.value
    this.setData({ deviceSecret: deviceConfig.deviceSecret })
  },
  //发布信息，开灯
  turnon: function () {
    const payloadJson = {
      id: Date.now(),
      params: {
        "Lightswitch": 1  //Lightswitch是与你的产品的物模型属性同名的
      },
      method: "thing.event.property.post"
    }
    client.publish(topics.pubTopic, JSON.stringify(payloadJson))
  },
  //发布信息，关灯
  turnoff: function () {
    const payloadJson = {
      id: Date.now(),
      params: {
        "Lightswitch": 0
      },
      method: "thing.event.property.post"
    }
    client.publish(topics.pubTopic, JSON.stringify(payloadJson))
  },
  online: function () {
    const _this = this
    const options = this.initMqttOptions(deviceConfig);
    //注意这里是 wxs，不是 wss，否则你可能会碰到 ws 不是构造函数的错误
    client = mqtt.connect(`wxs://${deviceConfig.productKey}.iot-as-mqtt.cn-shanghai.aliyuncs.com`, options)
    client.on('connect', function () {
      wx.showToast({
        title: '设备上线，连接服务器成功',
        duration: 2000,
        icon: "none"
      })
      //(这里的主题可能会不一样，具体请查看后台设备 Topic 列表或使用自定主题)
      client.subscribe(topics.subTopic, function (err) {
        if (!err) {
          console.log('订阅成功！');
        }
      })
    })
    //接收消息监听
    client.on('message', function (topic, message) {
      message = message.toString()
      message = JSON.parse(message) //将接收到的字符串进行 Json 格式转换
      console.log(message)   //建议打印出message的内容方便调试，查看经过你的规则引擎后得到的数据究竟是什么样的
      _this.setData({
        temperature: message['temp'],
        humidity: message['humi']
      })
    })
  },
  offline: function () {
    //client 连接断开,关闭连接
    client.end()
    this.setData({
      humidity: "",
      temperature: "",
    })
    wx.showToast({
      title: '设备断开连接',
      duration: 2000,
      icon: "none"
    })
  },
  //IoT 平台 mqtt 连接参数初始化
  initMqttOptions(deviceConfig) {
    const params = {
      productKey: deviceConfig.productKey,
      deviceName: deviceConfig.deviceName,
      timestamp: Date.now(),
      clientId: Math.random().toString(36).substr(2),
    }
    //CONNECT 参数
    const options = {
      keepalive: 60, //60s
      clean: true, //cleanSession 不保持持久会话
      protocolVersion: 4 //MQTT v3.1.1
    }
    //1.生成 clientId，username，password
    options.password = this.signHmacSha1(params, deviceConfig.deviceSecret);
    options.clientId = `${params.clientId}|securemode=2,signmethod=hmacsha1,timestamp=${params.timestamp}|`;
    options.username = `${params.deviceName}&${params.productKey}`;
    return options;
  },
  /*
  生成基于 HmacSha1 的 password
  参考文档：https://help.aliyun.com/document_detail/73742.html?#h2-url-1
  */
  signHmacSha1(params, deviceSecret) {
    let keys = Object.keys(params).sort();
    // 按字典序排序
    keys = keys.sort();
    const list = [];
    keys.map((key) => {
      list.push(`${key}${params[key]}`);
    });
    const contentStr = list.join('');
    return crypto.hex_hmac_sha1(deviceSecret, contentStr);
  }
})
